package com.hernie.piggymall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.hernie.common.utils.HttpUtils;
import com.hernie.common.utils.R;
import com.hernie.piggymall.auth.feign.MemberFeignService;
import com.hernie.common.vo.MemberRespVo;
import com.hernie.piggymall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author HuangJp
 * @Date 2022/4/11
 * @Description 处理社交登录请求
 */
@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    private MemberFeignService memberFeignService;

    /**
     * 社交登录
     * @param code
     * @return
     * @throws Exception
     */
    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("client_id", "");
        map.put("client_secret", "");
        map.put("grant_type", "");
        map.put("redirect_uri", "http://auth.piggymall.com/oauth2.0/weibo/success");
        map.put("code", code);
        // 根据code换取accessToken;
        HttpResponse response = HttpUtils.doPost("api.weibo.com", "/oauth2/access_token", "post", null, null, map);

        if (response.getStatusLine().getStatusCode() == 200) {
            // 获取到 accessToken
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);

            // 如果用户第一次进入网站，则自动注册进来，为当前社交登录账户生成一个对应的会员信息账号
            // 判断当前用户是登陆还是注册，关联用户的社交账户uid
            R r = memberFeignService.oauthLogin(socialUser);
            if (r.getCode() == 0) {
                MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {
                });
                log.info("登陆成功，用户信息：", data.toString());
                // 第一次使用session；命令浏览器保存 JSESSIONID这个cookie
                // 以后浏览器访问哪个网站就会带上该网站的cookie
                // 发卡的时候（指定域名为父域名），即使子域系统发的卡，也能让父域直接使用
                // 默认发的令牌。session作用域是子域
                // 默认保存到redis的序列化方式是jdk序列化
                session.setAttribute("loginUser", data);
                // 登录成功，跳到首页
                return "redirect:http://piggymall.com";
            } else {
                return "redirect:http://auth.piggymall.com/login.html";
            }

        } else {
            return "redirect:http://auth.piggymall.com/login.html";
        }


    }
}
